package tgc.edu.ljc.custom;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

public abstract class CommonController<T extends BaseEntity ,ID,Form extends CommonForm> {
	private Class<T> clazz=GenericsUtils.getSuperClassGenricType(getClass());
	@Autowired
	private CommonService<T, ID> baseService;
	
	
	@RequestMapping(value="/table")
	public void table() {
	}
	
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(JqGridParam jqGridParam) {
		Pageable pageable=jqGridParam.buildPageable();
		Page<T> page;
		if(jqGridParam.getSearch()) {
			@SuppressWarnings("unchecked")
			Specification<T> spec=jqGridParam.buildSpec();
			page=baseService.findAll(spec, pageable);
		}else {
			page=baseService.findAll(pageable);
		}
		return JqGridUtils.getResult(page);
	}
	
	
	@RequestMapping(value="/update")
	@ResponseBody
	public String save(Form form,ID id) throws InstantiationException, IllegalAccessException {
		T entity=clazz.newInstance();
		BeanUtils.copyProperties(form, entity);
		entity.setId(id);
		baseService.save(entity);
		return "OK";
	}
	
	@RequestMapping(value="/add")
	@ResponseBody
	public String add(Form form) throws InstantiationException, IllegalAccessException {
		T entity=clazz.newInstance();
		BeanUtils.copyProperties(form, entity);
		baseService.save(entity);
		return "OK";
	}
	
	@RequestMapping(value="/delete")
	@ResponseBody
	public String delete(ID id) {
		baseService.deleteById(id);
		return "OK";
	}
	
	
}
